import pygtk
pygtk.require ('2.0')
import gtk
import gtk.glade
import database

class Gui:
	def __init__(self):
		"""
		In this init the main window is displayed
		"""
		dic = {
			 "on_window_main_destroy" : (self.quit),
			 "on_menu_quit_activate" : (self.quit),
			 "on_menu_people_activate" : (self.show_people),
			 "on_ent_title_key_press_event" : (self.wait_for_return_key),
			 "on_treeview1_key_press_event" : (self.wait_for_keys),
			 "on_bt_task_ok_clicked" : (self.bt_task_ok_clicked),
			 "on_bt_task_cancel_clicked" : (self.bt_task_cancel_clicked),
		}

		self.photo_w=21
		self.photo_h=32

		self.xml = gtk.glade.XML("atasko.glade")
		self.xml.signal_autoconnect (dic)

		self.dialog_task = self.xml.get_widget('dialog_task')

		self.task_memo = gtk.TextBuffer()
		task_memo = self.xml.get_widget('ent_memo')
		task_memo.set_buffer(self.task_memo)

# Tasks TreeView
		self.treeview = self.xml.get_widget('treeview1')
        	self.tasks_liststore = gtk.ListStore(gtk.gdk.Pixbuf,int,str,gtk.gdk.Pixbuf)
		self.treeview.set_model(model=self.tasks_liststore)

	        cellicon1 = gtk.CellRendererPixbuf()
	        cell = gtk.CellRendererText()
		cell.set_property('single-paragraph-mode',True)
	        cellicon2 = gtk.CellRendererPixbuf()

	        column1 = gtk.TreeViewColumn('Owner',cellicon1,pixbuf=0)
	        column2 = gtk.TreeViewColumn('Task',cell,text=2)
	        column3 = gtk.TreeViewColumn('Worker',cellicon2,pixbuf=3)

       		self.treeview.append_column(column1)
       		self.treeview.append_column(column2)
       		self.treeview.append_column(column3)

    		self.null_photo=gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, self.photo_w,self.photo_h)
		self.null_photo.fill(0xffffffff)

		self.no_photo=gtk.gdk.pixbuf_new_from_file('./photos/nophoto.jpg').scale_simple(self.photo_w,self.photo_h,gtk.gdk.INTERP_BILINEAR)

		
		self.myself=self.find_myself()
		self.me_photo=gtk.gdk.pixbuf_new_from_file('./photos/alfonso.cala.icon.jpg').scale_simple(self.photo_w,self.photo_h,gtk.gdk.INTERP_BILINEAR)

# Tasks Load
		tasks=database.Task.select(database.Task.q.st_work!="c")
		for task in tasks:
		  i=self.tasks_liststore.append((self.null_photo,task.id,task.title,self.no_photo))

		self.task_iter=0

# Workers ComboBox	
		self.cbox_worker = self.xml.get_widget('cbox_worker')
        	self.workers_liststore = gtk.ListStore(int,str,gtk.gdk.Pixbuf)
		self.cbox_worker.set_model(model=self.workers_liststore)

		people=database.Person.select(database.Person.q.myself==False)
		self.workers_liststore.append((0,"Me",self.null_photo))
		for person in people:
		  self.workers_liststore.append((person.id,person.name,self.no_photo))
		
	        cellicon1 = gtk.CellRendererPixbuf()
	        cell = gtk.CellRendererText()

		self.cbox_worker.pack_start(cellicon1,False)
		self.cbox_worker.add_attribute(cellicon1, "pixbuf", 2)
		self.cbox_worker.pack_start(cell,False)
		self.cbox_worker.add_attribute(cell, "text", 1)

# Status Combobox
		self.cbox_status = self.xml.get_widget('cbox_status')
        	self.status_liststore = gtk.ListStore(str,str)
		self.cbox_status.set_model(model=self.status_liststore)
		self.status_liststore.append(("n","New"))
		self.status_liststore.append(("f","Forwarded"))
		self.status_liststore.append(("c","Closed"))
		self.cbox_status.pack_start(cell,False)
		self.cbox_status.add_attribute(cell, "text", 1)
		 

	def find_myself(self):
		people=database.Person.select(database.Person.q.myself==True)
		#FIX (use list)
		return people[0]

	def wait_for_return_key(self,widget,event):
		if (event.keyval == gtk.keysyms.Return):
			self.create_task(widget)

# TASK creation
	def create_task(self,widget):
		title=self.get_value("ent_title_main")
		task=database.Task(creator_id=self.myself.id,worker_id=1,title=title,st_work='n')
		i=self.tasks_liststore.append((self.null_photo,task.id,title,self.null_photo))
		self.set_text("ent_title_main","")
		return
# TASK deletion
	def delete_task(self,widget):
                (iter,id,title)=self.get_selected_item(widget)
                if iter > 0:
			self.tasks_liststore.remove(iter)
		task = database.Task.get(id)
		task.destroySelf()

        def get_selected_item(self,widget):
                selection=widget.get_selection()
		(model,iter)=selection.get_selected()
		id=model.get_value(iter,1)
		title=model.get_value(iter,2)
                return (iter,id,title)

	def wait_for_keys(self,widget,event):
		if (event.keyval == gtk.keysyms.Delete):
			self.delete_task(widget)			
		if (event.keyval == gtk.keysyms.Return):
			self.edit_task(widget)

# TASK edit
	def edit_task(self,widget):
                (self.task_iter,id,title)=self.get_selected_item(widget)
		task=database.Task.get(id)
		owner=database.Person.get(task.creator_id)

		index=0
		if task.worker_id:
			worker=database.Person.get(task.worker_id)
			index=self.match_store(self.workers_liststore,worker.id)
		self.set_combo('cbox_worker',index)

		index=self.match_store(self.status_liststore,task.st_work)
		self.set_combo('cbox_status',index)
	
		self.set_text('ent_title',task.title)
		self.set_text('lab_owner',owner.name)
		self.task_memo.set_text(task.memo)
		self.dialog_task.show()
		return

	def match_store(self,model,id):
		n=0
		for iter in model:
			print iter[0], id
			if iter[0] == id:
				break
			n=n+1
		#FIX		
		return n
		

	def bt_task_ok_clicked(self,widget):
		id=self.tasks_liststore.get_value(self.task_iter,1)
		title=self.get_value("ent_title")
		(start,end)=self.task_memo.get_bounds()
		memo=self.task_memo.get_text(start,end)
		index=self.get_combo("cbox_worker")		
		worker=self.workers_liststore[index][0]

		index=self.get_combo("cbox_status")		
		st_work=self.status_liststore[index][0]

		task=database.Task.get(id)
		task.set(title=title,memo=memo,worker_id=worker,st_work=st_work)
		self.tasks_liststore.set_value(self.task_iter,2,title)
		self.dialog_task.hide()
		return
		
	def bt_task_cancel_clicked(self,widget):
		self.dialog_task.hide()

	def show_people(self):
		#FIX
		return

        def set_text(self,widgetname,text):
		widget=self.xml.get_widget(widgetname)
                widget.set_text(text)
		return
	def get_value(self,widgetname):
        	widget=self.xml.get_widget(widgetname)
                return widget.get_text()
	def get_combo(self,widgetname):
        	widget=self.xml.get_widget(widgetname)
                return widget.get_active()
	def set_combo(self,widgetname,index):
        	widget=self.xml.get_widget(widgetname)
                widget.set_active(index)
                return                                                                 	

	def run(self):
		gtk.main()

	def quit(*args):
		if hasattr(gtk, 'main_quit'):
	            gtk.main_quit()
	        else:
	            gtk.mainquit()

